<template>
  <view>
    <mxp-popup ref="_payPopupRef" model="bottom" :height="`${popupHeight}px`" @hide="onHide">
      <template #header>
        <pay-popup-header
          :priceVirtualRate="priceVirtualRate"
          :height="headerHeight"
          :virtualcoinPrice="virtualcoinPrice"
          :paidTotal="dramaWaitUnlockNum"
          :allTotal="dramaEpisodeNum"
          :userVirtualCoins="userVirtualCoins"
          agreementName="充值服务协议"
          @agreementClick="openRechargeAgreementPopup"
          @hideClick="hideClick"
        ></pay-popup-header>
      </template>
      <mxp-refresh-scroll-view
        ref="mxpRefreshScrollViewRef"
        :height="`${scrollViewHeight}px`"
        :style="{ height: `${scrollViewHeight}px`, width: '750rpx' }"
        :queryData="queryData"
      >
        <template v-if="payList.length > 0">
          <view class="pay-list">
            <pay-select-item
              v-for="(item, index) in payList"
              :key="index"
              style="width: 100%"
              :active="currIndex === index"
              :productName="item.productName || ''"
              :productPrice="item.productPrice || ''"
              :productType="item.productType"
              :marketingDesc="item.marketingDesc || ''"
              :recommendTags="item.recommendTags || ''"
              unit="元"
              @myClick="changeMoney(index)"
            ></pay-select-item>
          </view>
          <view class="hint-box">
            <text class="title">温馨提示：</text>
            <text class="hint">1. 虚拟物品付费后不支持退款</text>
            <text class="hint">2. 付费解锁后可永久观看</text>
            <text class="hint">3. K币充值后不可反向兑换为人民币等其他法定货币</text>
            <text class="hint">4. 会员有效期内可免费观看无需付费解锁，会员过期后无法观看(已付费解锁剧集除外)</text>
            <text class="hint">5. 在播剧目{{ dramaOnlineNum }}部</text>
            <text class="hint">6. 未满18岁的未成年,应在监护人同意或授权下充值</text>
            <view class="agreement-box">
              <text class="hint">7. 充值代表同意</text>
              <text class="hint" :style="{ color: '#223aec' }" @click="openRechargeAgreementPopup">《充值服务协议》</text>
              <text class="hint">和</text>
              <text class="hint" :style="{ color: '#223aec' }" @click="openMembershipAgreementPopup">《VIP服务协议》</text>
            </view>
            <view v-if="isAutoPay" :style="{ height: `${safeAreaInsetBottom}px` }"></view>
          </view>
        </template>
      </mxp-refresh-scroll-view>
      <!-- 支付 -->
      <view v-if="!isAutoPay" class="bottom-box" :style="{ height: `${bottomHeight}px` }">
        <mxp-button text="余额解锁" fontSize="13px" width="200rpx" height="32px" @click="balanceUnlock"></mxp-button>
        <mxp-radio
          :checked="isAutoPay"
          :cusStyle="{ pointerEvents: 'auto' }"
          :loading="autoPayLoading"
          labelSize="12px"
          label="自动使用余额解锁"
          iconSize="18px"
          :labelColor="defThemeColor.text3"
          :beforeChange="switchBeforeChange"
        ></mxp-radio>
      </view>
      <view v-if="!isAutoPay" key="view-2" :style="{ height: `${safeAreaInsetBottom}px` }"></view>
    </mxp-popup>
    <!-- VIP服务协议 -->
    <membership-agreement-popup ref="membershipAgreementPopupRef" :height="popupHeight"></membership-agreement-popup>
    <!-- 充值服务协议 -->
    <recharge-agreement-popup ref="rechargeAgreementPopupRef" :height="popupHeight"></recharge-agreement-popup>
  </view>
</template>

<script setup lang="ts">
  import { computed, getCurrentInstance, ref } from 'vue';
  import PayPopupHeader from '@/components/pay/pay-popup-header/pay-popup-header.vue';
  import MxpPopup from '@/mxp-ui/mxp-popup/mxp-popup.vue';
  import PaySelectItem from '@/components/pay/pay-select-item/pay-select-item.vue';
  import MxpRadio from '@/mxp-ui/mxp-radio/mxp-radio.vue';
  import MembershipAgreementPopup from '@/components/page/membership-agreement/membership-agreement-popup.vue';
  import RechargeAgreementPopup from '@/components/page/recharge-agreement/recharge-agreement-popup.vue';
  import MxpButton from '@/mxp-ui/mxp-button/mxp-button.vue';
  import {
    type KsBalanceunlockInfo,
    type Product,
    createKsBalanceOrderAxios,
    getDramaCommodityInfoAxios,
    ksCreateEpisodePayOrderAxios,
    queryDramaKsPayResultAxios,
  } from '@/api/pay';
  import { ksPay } from '@/utils/payUtil';
  import { useAppStore } from '@/pinia/app';
  import type { ShowEvent } from '../util';
  import { sleep } from '@/mxp-ui/mxp-tool/utils/rest';
  import { autoLogin, updateUserInfo } from '@/utils/page/user';
  import mxpGetSysInfoStore from '@/mxp-ui/mxp-tool/store/mxp-store-sys-info';
  import { amendAutoPayAxios } from '@/api/account';
  import { defThemeColor } from '@/mxp-ui/mxp-tool/theme/theme';
  import MxpRefreshScrollView, { type Ins } from '@/mxp-ui/mxp-refresh-scroll-view/mxp-refresh-scroll-view.vue';
  import { eventTrackingPayTemplateAxios } from '@/api/drama';
  defineOptions({
    name: 'pay-popup',
  });

  const props = defineProps({
    /** 第三方剧目id */
    thirdDramaId: { type: String, required: true },
    /** 当前剧集下标 */
    currEpisodeIndex: { type: Number, required: true },
  });

  const mxpRefreshScrollViewRef = ref<InstanceType<typeof MxpRefreshScrollView>>();

  const sys = mxpGetSysInfoStore().getSysInfo();
  /** 上线剧目数量 */
  const dramaOnlineNum = ref(1);
  /** 待解锁剧集数量 */
  const dramaWaitUnlockNum = ref(0);
  /** 广告解锁：0-不支持；1-支持； */
  const advertUnlock = ref<0 | 1>(0);
  /** 短剧标题 */
  const dramaTitle = ref<string | undefined>(undefined);
  /** 是否可以支付 */
  const isPay = ref(true);
  const appStore = useAppStore();
  const payList = ref<Product[]>([]);
  const loading = ref(false);
  const safeAreaInsetBottom = computed(() => sys.value.safeAreaInsets?.bottom || 0);
  const membershipAgreementPopupRef = ref<InstanceType<typeof MembershipAgreementPopup> | null>(null);
  const rechargeAgreementPopupRef = ref<InstanceType<typeof RechargeAgreementPopup> | null>(null);
  const dramaEpisodeNum = ref(0);
  /** 是否自动解锁 */
  const isAutoPay = computed(() => appStore.userInfo?.isAutoPay === 1);
  /** 单集解锁价格 */
  const virtualcoinPrice = ref<number | string>('--');
  /** 用户余额 */
  const userVirtualCoins = computed(() => appStore.userInfo?.virtualCoins);

  const scrollViewHeight = computed(() => 3 * 100 + 2 * 15 + 40 + (isAutoPay.value ? 40 : 0));
  const headerHeight = 150;
  const bottomHeight = computed(() => (isAutoPay.value ? 0 : 40));
  const popupHeight = computed(() => scrollViewHeight.value + headerHeight + bottomHeight.value + (!isAutoPay.value ? safeAreaInsetBottom.value : 0));

  const autoPayLoading = ref(false);
  const _payPopupRef = ref<InstanceType<typeof MxpPopup> | null>(null);
  const currIndex = ref(0);

  const priceVirtualRate = ref(100);

  /** 支付成功的回调 */
  let paySuccess: ShowEvent['paySuccess'] | undefined = undefined;
  /** 广告解锁回调 */
  let adUnlock: ShowEvent['adUnlock'] | undefined = undefined;

  const instance = getCurrentInstance();
  /** 显示 */
  function show(data: ShowEvent) {
    dramaTitle.value = data.dramaTitle;
    paySuccess = data.paySuccess;
    adUnlock = data.adUnlock;
    currIndex.value = 0;
    if (!_payPopupRef.value && instance?.proxy?.$refs?._payPopupRef) {
      _payPopupRef.value = instance?.proxy.$refs._payPopupRef as InstanceType<typeof MxpPopup>;
    }
    _payPopupRef.value?.show();

    eventTrackingPayTemplateAxios({
      referralLinkId: appStore.launchQuery?.referralLinkId,
      playletId: props.thirdDramaId!,
      episodeSeq: props.currEpisodeIndex + 1,
    });
  }

  /**
   * 监听隐藏
   */
  function onHide(type: 'button' | 'confirm' | 'mask' | 'rest') {
    if (type === 'mask') {
      advertUnlock.value === 1 && typeof adUnlock === 'function' && adUnlock();
    }
  }

  /** 查询支付状态以及支付后的短剧 */
  async function queryPayOrder(outTradeNo: string): Promise<number[]> {
    await sleep(1000); // 延迟两秒查询
    const queryRes = await queryDramaKsPayResultAxios({ outTradeNo, thirdDramaId: props.thirdDramaId! });
    appStore.updateVirtualCoins(queryRes.data.virtualCoins || appStore.userInfo?.virtualCoins || 0);
    let payEpisodeList: number[] = [];
    if (queryRes.data.status === 1) {
      if (queryRes.data.productType === 1) {
        try {
          const res: KsBalanceunlockInfo = await createDyBalanceOrder();
          payEpisodeList = res.payEpisodeList;
        } catch (error) {
          return Promise.reject({ code: error.code || -2001, msg: error.msg || '解锁失败' });
        }
      } else if (queryRes.data.productType === 2) {
        payEpisodeList = queryRes.data.payEpisodeList;
        uni.showToast({ title: `开通会员成功`, icon: 'none', position: 'bottom' });
      } else if (queryRes.data.productType === 3) {
        payEpisodeList = queryRes.data.payEpisodeList;
        uni.showToast({ title: `您已解锁全集`, icon: 'none', position: 'bottom' });
      } else {
        payEpisodeList = queryRes.data.payEpisodeList;
        uni.showToast({ title: `操作成功`, icon: 'none', position: 'bottom' });
      }
      return Promise.resolve(payEpisodeList);
    } else {
      return Promise.reject({ code: -1001, msg: '支付失败，BD10002' });
    }
  }

  /** 余额解锁 */
  async function balanceUnlock() {
    try {
      await createDyBalanceOrder();
      hide();
    } catch (error) {
      uni.showToast({ title: error.msg, icon: 'none', position: 'bottom' });
    }
  }

  /** 余额解锁 */
  async function createDyBalanceOrder(): Promise<KsBalanceunlockInfo> {
    try {
      const res = await createKsBalanceOrderAxios({
        thirdDramaId: props.thirdDramaId!,
        episodeSeq: props.currEpisodeIndex + 1,
        referralLinkId: appStore.launchQuery?.referralLinkId,
      });
      if (res.data.unLockStatus === 1) {
        appStore.updateVirtualCoins(res.data.virtualCoins);
        uni.showToast({ title: '解锁成功', icon: 'none', position: 'bottom' });
        return Promise.resolve(res.data);
      } else {
        return Promise.reject({ code: -1001, msg: '余额不足或解锁失败,BDZS001' });
      }
    } catch (error) {
      console.log('K币解锁失败====', error);
      return Promise.reject({ code: -1001, msg: error.msg || 'K币解锁失败,BDZS002' });
    }
  }

  /** 支付关闭 */
  function hideClick() {
    hide();
    advertUnlock.value === 1 && typeof adUnlock === 'function' && adUnlock();
  }

  /** 切换支付 */
  async function changeMoney(index: number) {
    if (!loading.value) {
      currIndex.value = index;
      if (isPay.value) {
        const item = payList.value[currIndex.value]!;
        try {
          loading.value = true;
          uni.showLoading({ title: '加载中', mask: true });
          const ksOrder = await ksCreateEpisodePayOrderAxios({
            thirdDramaId: props.thirdDramaId,
            referralLinkId: appStore.launchQuery?.referralLinkId,
            productType: item.productType,
            episodeSeq: props.currEpisodeIndex + 1,
            productId: item.productId,
            devicePlatform: sys.value.platform === 'devtools' ? sys.value.osName : sys.value.platform,
          });

          await ksPay({ order_no: ksOrder.data.transactionId!, order_info_token: ksOrder.data.orderInfoToken! });
          uni.showLoading({ title: '正在获取支付结果', mask: true });
          const res = await queryPayOrder(ksOrder.data.outTradeNo!);
          loading.value = false;
          hide();
          updateUserInfo(); // 更新个人资料
          uni.hideLoading();
          typeof paySuccess === 'function' && paySuccess(res);
        } catch (error) {
          uni.hideLoading();
          loading.value = false;
          console.log('解锁失败====', error);
          uni.showToast({ title: error.msg || '操作失败', icon: 'none', position: 'bottom' });
        }
      } else {
        uni.showToast({ title: '由于平台限制,暂不支持支付', icon: 'none', position: 'bottom' });
      }
    }
  }

  /** 隐藏 */
  function hide() {
    _payPopupRef.value?.hide();
  }

  /** 打开充值服务协议 */
  function openRechargeAgreementPopup() {
    rechargeAgreementPopupRef.value?.show();
  }
  /** 打开会员服务协议 */
  function openMembershipAgreementPopup() {
    membershipAgreementPopupRef.value?.show();
  }

  /** 修改自动解锁 */
  async function switchBeforeChange() {
    try {
      autoPayLoading.value = true;
      const res = await amendAutoPayAxios();
      appStore.updateIsAutoPay(res.data);
      autoPayLoading.value = false;
      return Promise.resolve(res.data === 1);
    } catch (error) {
      autoPayLoading.value = false;
      return Promise.reject(true);
    }
  }
  /** 加载中 */
  async function queryData(ins: Ins | null | undefined) {
    try {
      if (payList.value.length <= 0) {
        !appStore.loginState && (await autoLogin());
        const res = await getDramaCommodityInfoAxios({
          referralLinkId: appStore.launchQuery?.referralLinkId,
          thirdDramaId: props.thirdDramaId,
          devicePlatform: sys.value.platform === 'devtools' ? sys.value.osName : sys.value.platform,
          wxFinderId: appStore.launchQuery?.wxFinderId,
          wxExportId: appStore.launchQuery?.wxExportId,
          wxPromotionId: appStore.launchQuery?.wxPromotionId,
        });
        priceVirtualRate.value = Number(appStore.baseDictInfo?.PRICE_VIRTUAL_RATE || 100);
        payList.value = res.data.productList || [];
        currIndex.value = res.data.selectIndex;
        advertUnlock.value = res.data.advertUnlock === 1 ? 1 : 0;
        virtualcoinPrice.value = res.data.virtualCoin || '--';
        appStore.updateVirtualCoins(res.data.userVirtualCoins || appStore.userInfo?.virtualCoins || 0);
        isPay.value = res.data.pay;
        dramaEpisodeNum.value = res.data.dramaEpisodeNum || 0;
        dramaOnlineNum.value = res.data.dramaOnlineNum || 0;
        dramaWaitUnlockNum.value = res.data.dramaWaitUnlockNum || 0;
      }
      ins?.setSuccess();
    } catch (error) {
      payList.value = [];
      ins?.setEmpty('fail_load', error.msg || '获取数据失败，BD0001');
    }
  }

  defineExpose({
    /** 显示 */
    show,
    /** 隐藏 */
    hide,
  });
</script>

<style lang="scss" scoped>
  .pay-list {
    display: grid;
    grid-template-columns: repeat(2, 1fr);
    grid-gap: 15px;
    justify-content: space-between;
    justify-items: center;
    padding: 15px;
  }

  .hint-box {
    display: flex;
    flex-direction: column;
    padding: 15px;
    padding-top: 0;

    .title {
      margin-bottom: 6px;
      font-size: 12px;
      font-weight: bold;
      color: #666666;
      word-break: break-all;
      word-wrap: break-word;
      white-space: normal !important;
    }

    .hint {
      margin-bottom: 6px;
      font-size: 12px;
      color: #999999;
      word-break: break-all;
      word-wrap: break-word;
      white-space: normal !important;
    }

    .agreement-box {
      display: flex;
      flex-direction: row;
      align-items: center;
    }
  }

  .bottom-box {
    box-sizing: border-box;
    display: flex;
    flex-direction: row;
    align-items: center;
    justify-content: space-between;
    width: 750rpx;
    padding: 0 15px;
  }
</style>
